package cn.tedu.order.service;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.util.JsonUtil;
import cn.tedu.order.util.RedisUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

@Service
public class OrderServiceImpl implements OrderService{
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private RedisUtil redisUtil;

    @Transactional //控制本地事务
    @GlobalTransactional //开启全局事务，只在第一个模块添加
    @Override
    public void create(Order order) {
        //远程调用发号器生成订单id
        String s = easyIdClient.nextId("order_business");
        Long orderId = Long.valueOf(s);
        // 临时随机生成一个id,添加发号器后这行代码删除
        order.setId(orderId);
        orderMapper.create(order);


        // 调用库存减少商品库存
        storageClient.decrease(order.getProductId(), order.getCount());
        // 调用账户减少账户金额
        accountClient.decrease(order.getUserId(), order.getMoney());
        //在redis也存一份订单数据
        redisUtil.set(""+orderId, JsonUtil.to(order));
    }

    @Override
    public Order findById(Long id) {
        //1.从redis查询
        String json = (String) redisUtil.get("" + id);

        //2.如果有数据直接返回
        if (json != null ){
            return JsonUtil.from(json, Order.class);
        }
        //3.如果redis没有数据，从数据库查询
        Order order=orderMapper.selectById(id);
        //4.把数据加入redis缓存
        redisUtil.set(""+id, JsonUtil.to(order));
        //5.返回
        return order;
    }
}
